using System;
using System.Data;
using System.Runtime.Serialization;
using System.Xml;

namespace MyConsole;
public static class ModuleCls
{


    /// <summary>
    /// 将对象转化为DataTable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="name">DataTable的名称</typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static DataTable ToDataTable<T>(this T obj, string name = "NewDataSet") where T : class, new()
    {
        var type = typeof(T);
        var propertise = type.GetProperties();
        var dt = new DataTable(name);
        foreach (var prop in propertise)
        {
            var column = new DataColumn { ColumnName = prop.Name, DataType = prop.PropertyType };
            dt.Columns.Add(column);
        }
        var dr = dt.NewRow();
        foreach (var prop in propertise)
        {
            var val = prop.GetValue(obj, null);
            if (val == null && prop.PropertyType == typeof(string)) val = " ";      // 如果值为空而且类型是字符串，则设置为空格
            dr[prop.Name] = val;
        }
        dt.Rows.Add(dr);
        return dt;
    }


    public static string ToXml<T>(this T obj)
    {
        var serializer = new DataContractSerializer(obj.GetType());
        using (var writer = new StringWriter())
        using (var stm = new XmlTextWriter(writer))
        {
            serializer.WriteObject(stm, obj);
            return writer.ToString();
        }
    }

}